# -*- encoding:utf-8 -*-
import base64
import poplib
import re
from email import parser

# base64解码(递归解码)
def basedecode(s):
    strs = re.findall("=\?\\w+[-]?\\w+\?\\w+\?.*?\?=", s)
    if strs != []:
        for str in strs:
            cont = str
            base2str = re.compile('=\?\\w+[-]?\\w+\?\\w+\?').split(cont)[1]
            # print base2str[:-2]
            s = re.sub(re.escape(cont), base64.b64decode(base2str[:-2]), s)
            # print base64.b64decode(base2str[:-2])

    return s

# 内容解析
def base2content(message,str1):
    if type(message._payload) == type(''):
        if len(message._payload.replace('\n', '')) % 4 == 0 and len(message._payload.replace('\n', '')) != 0:
            str1+=base64.b64decode(message._payload)
        else:
            str1+=message._payload
    else:
        for msg in message._payload:
            str1+=base2content(msg,str1)
    return str1

# 格式统一化
def recordinfile(msg):
    str=''
    str+='Subject :'+basedecode(msg['Subject'])+'\n'
    str+='From :'+basedecode(msg['From'])+'\n'
    str+='To :'+basedecode(msg['To'])+'\n'
    str+='Date :'+basedecode(msg['Date'])+'\n'
    str+='Content :'+base2content(msg,'')
    return str


host = "mail.bupt.edu.cn"

username = "manatea@bupt.edu.cn"

password = ""

session = poplib.POP3(host)

session.set_debuglevel(1)

session.user(username)
session.pass_(password)

# 获取邮件信息（数量，大小）
ret = session.stat()

print ret
# for i in range(1, 5):
#     print "------------------------------------id:%d----------------------------头信息" % i
#     for cont in session.top(i, 0)[1]:
#         cont = basedecode(cont)
#         print "another ", cont
# if cont[0:5] == "From:":
#     print cont
# elif cont[0:3].lower() == "to:":
#     print cont
# elif cont[0:5] == "Date:":
#     print cont
# elif cont[0:8] == "Subject:":
#     print cont
# print "--------------------------------内容------------------------------------->"

# 获取文件列表，并用email.parser解析
messages = [session.retr(i) for i in range(1, ret[0] + 1)]
messages = ["\n".join(mssg[1]) for mssg in messages]
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
# 封装后存入文件
for i in range(len(messages)):
    str='------------------------------------id:%d----------------------------' % i +'\n'
    str+= recordinfile(messages[i])
    str+='\n'
    f = open('1.txt','a+')
    f.writelines(str)
    f.close()

# down = session.retr(i)
# message = "\n".join(down[1])
# message = parser.Parser().parsestr(message)
# base2content(message)
# print base64.b64decode(message['_payload'])
# for msg in messages:
#     print msg





session.quit()
